import { PlusOutlined, LoadingOutlined } from "@ant-design/icons";
import { Upload, message } from "antd";
import { useState } from "react";
import React, { Component } from "react";
import Cloud from "leancloud-storage";

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = (file) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("You can only upload JPG/PNG file!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("照片太大了");
  }
  return isJpgOrPng && isLt2M;
};

class UploadImg extends Component {
  state = {
    loading: false,
    imageUrl: "",
  };
  handleUp = (info) => {
    console.log(info);
    getBase64(info.file, async (base64) => {
      const file = await new Cloud.File("courseImg", { base64 }).save();
      this.props.onChange(file.attributes.url);
      this.setState({
        imageUrl: file.attributes.url,
      });
    });
  };
  render() {
    return (
      <>
        <Upload
          name="avatar"
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          beforeUpload={beforeUpload}
          customRequest={this.handleUp}
        >
          {this.state.imageUrl ? (
            <img
              src={this.state.imageUrl}
              alt="avatar"
              style={{
                width: "100%",
              }}
            />
          ) : (
            <div>
              {this.loading ? <LoadingOutlined /> : <PlusOutlined />}
              <div
                style={{
                  marginTop: 8,
                }}
              >
                上传封面
              </div>
            </div>
          )}
        </Upload>
      </>
    );
  }
}

export default UploadImg;
